package com.everflourish.yeah100.act.questionlib;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseActivity;
import com.everflourish.yeah100.adapter.QuestionBankDetailAdapter;
import com.everflourish.yeah100.entity.question.Question;
import com.everflourish.yeah100.entity.question.QuestionTag;
import com.everflourish.yeah100.http.QuestionRequest;
import com.everflourish.yeah100.ui.AutoLoadRecylerView;
import com.everflourish.yeah100.ui.animator.CustomItemAnimator;
import com.everflourish.yeah100.utils.IntentUtil;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者：Created by liqisi on 2016/7/29.
 * 时间：2016/7/29
 */
public class QuestionBankDetailActivity extends BaseActivity implements AutoLoadRecylerView.LoadMoreListener {

    private Toolbar mToolBar;
    private AutoLoadRecylerView mQuestionRecylerView;
    public SwipeRefreshLayout mSwipeRefreshLayout;
    public SwipeRefreshLayout.OnRefreshListener mRefreshListener;
    private TextView mEmptyTv;
    private QuestionBankDetailAdapter mAdapter;
    private List<Question> mList;
    public QuestionRequest mRequest;
    private String mTagId;
    private QuestionTag mQuestionTag;
    private boolean isLoadMore = false;  // 是否加载更多
    private boolean isRefreshOrLoadMore = false;  // 是否在刷新或者加载
    public boolean isUpdate;  // 是否更新

    /**
     * 每次加载10条
     */
    private int mSelectCount = 10;
    /**
     * 加载的位置
     */
    private int mStartIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_question_bank_detail);
        initData();
        initView();
        configView();
    }

    private void initData() {
        mRequest = QuestionRequest.getInstance();
        mTagId = getIntent().getStringExtra(IntentUtil.QUESTION_TAG_ID);
        mQuestionTag = (QuestionTag) getIntent().getSerializableExtra(IntentUtil.QUESTION);
        mList = new ArrayList<Question>();
        mAdapter = new QuestionBankDetailAdapter(mContext, mList, this, mQuestionTag.getTagId());
    }

    private void initView() {
        mEmptyTv = (TextView) findViewById(R.id.question_bank_empty_tv);
        mToolBar = (Toolbar) findViewById(R.id.toolbar_question_bank_detail);
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.question_bank_list_swipe);
        mQuestionRecylerView = (AutoLoadRecylerView) findViewById(R.id.question_bank_detail_list);
        mToolBar.setTitle(mQuestionTag.getTagName());
        setSupportActionBar(mToolBar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishMenuActivity();
            }
        });
    }

    private void configView() {
        mQuestionRecylerView.setLayoutManager(new LinearLayoutManager(this));
        mQuestionRecylerView.setItemAnimator(new CustomItemAnimator());
        mQuestionRecylerView.setAdapter(mAdapter);
        mRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getQuestionBankDetailList();
            }
        };
        mSwipeRefreshLayout.setColorScheme(R.color.colorAccent);
        mSwipeRefreshLayout.setOnRefreshListener(mRefreshListener);
        mSwipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setRefreshing(true);
            }
        });
        mRefreshListener.onRefresh();
        mQuestionRecylerView.setVisibility(View.GONE);
    }

    @Override
    public void onLoadMore() {
        isLoadMore = true;
        if (!isRefreshOrLoadMore) {
            getQuestionBankDetailList();
        }
    }

    public void getQuestionBankDetailList() {
        if (isLoadMore) {  // 加载更多
            mStartIndex = mStartIndex + mSelectCount;
        } else { // 下拉刷新
            mStartIndex = 0;
        }
        getQuestionBankDetailRequest(mStartIndex, mSelectCount);
    }

    private void getQuestionBankDetailRequest(int startIndex, int selectCount) {
        isRefreshOrLoadMore = true;
        mEmptyTv.setVisibility(View.GONE);
        JsonObjectRequest request = mRequest
                .getQuestionBankDetailRequest(startIndex, selectCount, mTagId, null,
                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                questionBankDetail(response);
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                isRefreshOrLoadMore = false;
                                isLoadMore = false;
                                mRequest.disposeError(mContext, null, error, "获取题目列表失败");
                                mSwipeRefreshLayout.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        mSwipeRefreshLayout.setRefreshing(false);
                                    }
                                });
                                mQuestionRecylerView.setLoading(false);
                            }
                        });
        mQueue.add(request);
    }

    /**
     * 获取题目列表监听
     *
     * @param response
     */
    private void questionBankDetail(JSONObject response) {
        int totalCount = 0;
        try {
            String resultCode = response.getString(Constant.RESULT_CODE);
            totalCount = response.getInt(Constant.TOTALCOUNT);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                JSONArray jsonArray = response
                        .getJSONArray(Constant.QUESTIONSLIST);
                Gson gson = new Gson();
                Type type = new TypeToken<List<Question>>() {
                }.getType();
                List<Question> questionListList = gson.fromJson(
                        jsonArray.toString(), type);
                if (questionListList == null || questionListList.size() == 0) {
                    mEmptyTv.setVisibility(View.VISIBLE);
                    mList.clear();
                }
                if (!isLoadMore) {
                    mList.clear();
                }
                mList.addAll(questionListList);
                mAdapter.notifyDataSetChanged();
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09101_000001E);
            } else if (resultCode.equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.questionlib_091099_999999E);
            } else {
                MyToast.showShort(mContext, "获取题目列表失败");
            }
        } catch (Exception e) {
            LogUtil.e("Json异常", e);
            MyToast.showShort(mContext, "获取题目列表失败");
        } finally {
            isRefreshOrLoadMore = false;
            isLoadMore = false;
            mQuestionRecylerView.setLoading(false);
            mQuestionRecylerView.setVisibility(View.VISIBLE);
            mAdapter.notifyItemRangeInserted(0, mList.size() - 1);
            mSwipeRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            });
            if (mList.size() >= totalCount) {
                mQuestionRecylerView.setLoadMoreListener(null);
            } else {
                mQuestionRecylerView.setLoadMoreListener(this);
            }
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finishMenuActivity();
            return true;
        } else {
            return super.onKeyUp(keyCode, event);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    /**
     * 设置关闭activity的数据
     */
    private void finishMenuActivity() {
        Intent resultIntent = getIntent();
        resultIntent.putExtra(IntentUtil.QUESTION_IS_UPDATE, isUpdate);
        this.setResult(RESULT_OK, resultIntent);
        IntentUtil.finishActivity(QuestionBankDetailActivity.this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mQueue.stop();
    }

}
